package com.spzx.product.controller;

import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ClassName: ChannelController
 * Package: com.spzx.product.controller
 * Description:
 *
 * @Author 王颖轩
 * @Create 2024/12/24 18:55
 * @Version 1.0
 */
@Tag(name = "聚合数据")
@RestController
@RequestMapping("/channel")
@Slf4j
public class ChannelController extends BaseController {
    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private IProductService productService;

    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IProductDetailsService productDetailsService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Operation(summary = "获取首页数据")
    @GetMapping("/index")
    public AjaxResult index() {
        List<CategoryVo> levelOneCategory = categoryService.getLevelOneCategory();
        IndexDataVo indexDataVo = new IndexDataVo();
        List<ProductSkuVo> topSale = productSkuService.getTopSale();

        indexDataVo.setCategoryList(levelOneCategory);
        indexDataVo.setProductSkuList(topSale);
        return success(indexDataVo);
    }

    @Operation(summary = "获取分页嵌套列表")
    @GetMapping("/category")
    public AjaxResult category() {
        return success(categoryService.tree());
    }

    @Operation(summary = "获取品牌信息")
    @GetMapping("/brand")
    public AjaxResult selectBrandAll() {
        return success(brandService.list());
    }

    @Operation(summary = "显示商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(
            @Parameter(description = "当前页码")
            @PathVariable Integer pageNum,

            @Parameter(description = "每页记录数")
            @PathVariable Integer pageSize,

            SkuQuery skuQuery) {

        PageHelper.startPage(pageNum, pageSize);
        List<ProductSkuVo> list = productSkuService.selectProductSkuList(skuQuery);
        return getDataTable(list);
    }

    @Operation(summary = "商品详情")
    @GetMapping("/item/{skuId}")
    public AjaxResult item( @Parameter(description = "skuId")
                                @PathVariable Long skuId) {
        try {
            ItemVo itemVo = new ItemVo();

            CompletableFuture<Long> futureProductSku = CompletableFuture.supplyAsync(() -> {
                //获取sku信息
                ProductSku productSku = productSkuService.getProductSku(skuId);
                itemVo.setProductSku(productSku);

                return productSku.getProductId();
            }, threadPoolExecutor);

            CompletableFuture<Void> futureSkuPrice = CompletableFuture.runAsync(() -> {
                //获取商品最新价格
                SkuPriceVo skuPriceVo = productSkuService.getSkuPrice(skuId);
                itemVo.setSkuPrice(skuPriceVo);
            }, threadPoolExecutor);


            CompletableFuture<Void> futureSkuStock = CompletableFuture.runAsync(()->{
                //获取商品库存信息
                SkuStockVo skuStockVo = skuStockService.getSkuStock(skuId);
                itemVo.setSkuStock(skuStockVo);
            }, threadPoolExecutor);

            CompletableFuture<Void> futureProduct = futureProductSku.thenAcceptAsync(productId -> {
                //获取商品信息
                Product product = productService.getById(productId);
                //商品幻灯片图片列表
                String[] sliderUrlList = product.getSliderUrls().split(",");
                itemVo.setSliderUrlList(sliderUrlList);
                //商品规格
                JSONArray specValueList = JSONArray.parse(product.getSpecValue());
                itemVo.setSpecValueList(specValueList);
            });

            CompletableFuture<Void> futureDetailsImageUrlList = futureProductSku.thenAcceptAsync(productId -> {
                //商品详情图片
                String[] detailsImageUrlList = productDetailsService.getDetailsImageUrlList(productId);
                itemVo.setDetailsImageUrlList(detailsImageUrlList);
            });

            CompletableFuture<Void> futureSkuSpecValueMap = futureProductSku.thenAcceptAsync(productId -> {
                //商品规格Map：
                //key: 规格字符串
                //value：skuId
                Map<String, Long> skuSpecValueMap = productSkuService.getSkuSpecValueMap(productId);
                itemVo.setSkuSpecValueMap(skuSpecValueMap);
            });


            CompletableFuture.allOf(
                    futureProductSku,
                    futureSkuPrice,
                    futureSkuStock,
                    futureProduct,
                    futureDetailsImageUrlList,
                    futureSkuSpecValueMap).join();
            return success(itemVo);
        } catch (Exception e) {
            log.error("获取商品详情异常{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        }
    }
}
